import React, {Component} from 'react'
import PropTypes from 'prop-types'
import './index.css'

export default class Footer extends Component {
  static propTypes = {
    todos: PropTypes.array.isRequired,
    setAllToDoTrue: PropTypes.func,
    clearAllDoneTodo: PropTypes.func
  }

  setAllToDoTrue = this.props.setAllToDoTrue
  clearAllDoneTodo = this.props.clearAllDoneTodo

  render() {
    const todos = this.props.todos
    return (
      <div className="todo-footer">
        <label>
          <input type="checkbox" onChange={this.handleChange} checked={this.computedDoneCount() === todos.length}/>
        </label>
        <span>
          <span>已完成{this.computedDoneCount()}</span> / 全部{todos.length}
        </span>
        <button className="btn btn-danger" onClick={this.handleClear}>清除已完成任务</button>
      </div>
    )
  }

  // 计算已完成的数量
  computedDoneCount = () => {
    const todos = this.props.todos
    return todos.reduce((pre, todo) => {
      return todo.done ? pre + 1 : pre
    }, 0)
  }

  handleChange = (e) => {
    const {checked} = e.target
    this.setAllToDoTrue(checked)
  }

  handleClear = () => {
    this.clearAllDoneTodo()
  }
}
